<?php
App::import("vendor","Deals.DealOrderPayment");
class DealOrdersController extends DealsAppController 
{

	var $name = 'DealOrders';
	var $helpers = array('Html', 'Form', 'Cms.Index');
	var $components = array('Auth','Session','RequestHandler','Email');
	
	function beforeFilter()
	{
		$this->Auth->allow('index','view','paypalReturn','paypalIpn');
		$this->Auth->loginAction = array("plugin"=>"users","controller"=>"users",'action'=>'login');
		parent::beforeFilter();
	}

	function add($dealId = null)
	{
		if(!$this->DealOrder->Deal->isDealEnabled())
		{
			$this->errorMsg(__('Deals functionality is not enabled', true));
			$this->redirect($this->referer("/"));
		}
		$this->DealOrder->Deal->recursive = 0;
		$deal = $this->DealOrder->Deal->findById($dealId);
		$authedUserId = $this->Session->read("Auth.User.id");
		if(!$authedUserId)
		{
			$this->errorMsg(__('Only logged in users are allowed to purchase', true));
			$this->redirect($this->referer("/"));
			return;
		}
		if(!$dealId || !$deal)
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect($this->referer("/"));
			return;
		}
		if($this->DealOrder->Deal->hasExpired($dealId))
		{
			$this->errorMsg(__('Deal has already expired'));
			$this->redirect($this->referer("/"));
			//$this->redirect(array("plugin"=>"deals","controller"=>"deals",'action'=>'view',$deal['Deal']['id']));
			return;
		}
		if(!$this->DealOrder->Deal->canBePurchased($dealId))
		{
			$this->errorMsg(__("Deal quantity exhausted.", true));
			$this->redirect($this->referer("/"));
			//$this->redirect(array("plugin"=>"deals","controller"=>"deals",'action'=>'view',$deal['Deal']['id']));
			return;
		}
		
		$this->pageTitle = sprintf(__("Buy Deal - %s"), $deal['Deal']['title']);
		if (!empty($this->data)) 
		{
			$save = true;
			if(!preg_match("/^\d+$/", $this->data['DealOrder']['quantity'])) 
			{
				$save = false;
				$this->errorMsg(__("Please enter a valid quantity to be purchased. (minimum value is 1).", true));
			} else {
				if(!$this->DealOrder->Deal->canBePurchased($dealId, $this->data['DealOrder']['quantity']))
				{
					$save = false;
					$this->errorMsg(__("Requested quantity is more than available/remaining deal quantity"));
				}
			}
			if($save)
			{
				$this->data['DealOrder']['deal_id'] = $dealId;
				$this->data['DealOrder']['user_id'] = $authedUserId;
				$this->data['DealOrder']['status'] = DealOrder::STATUS_PENDING;
				if ($this->DealOrder->saveOrder($this->data)) 
				{
					$this->SuccessMsg(__("Please wait while we are redirecting you to payment process."));
					$this->redirect(array("plugin"=>"deals","controller"=>"deal_orders",'action'=>'prepareInvoice',$this->DealOrder->id));
				} else {
					$this->errorMsg(__("An error has occured while purchasing the deal. Please try again."));
				}
			}
		}
		$this->set(compact('deal'));
	}
	
	function admin_index($dealId = null) 
	{
		$deal = $this->DealOrder->Deal->findById($dealId);
		/*
		if(!$dealId || empty($deal))
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect(array("controller"=>"backend","action"=>"index"));
		}
		*/
		$conditions = array('DealOrder.status' => DealOrder::STATUS_COMPLETE);
		$pageTitle = __("All Orders");
		if($dealId && !empty($deal))
		{
			$conditions[] = array('DealOrder.deal_id'=>$dealId);
			$pageTitle = sprintf(__("Orders for %s"),$deal['Deal']['title']);
		}
		$this->pageTitle = $pageTitle;
		if(!isset($this->paginate['conditions']))
		{
			$this->paginate['conditions'] = array();
		}
		$this->paginate['conditions'] = am($this->paginate['conditions'],$conditions);
		$this->paginate['order'] = array('DealOrder.created'=>"DESC");
		$dealOrders = $this->paginate();
		$this->set('dealOrders', $dealOrders);
		$this->set('deal', $deal);
	}
	
	function admin_changeStatus($id)
	{
		$dealOrder = $this->DealOrder->find('first',array('conditions'=>array('DealOrder.id'=>$id,'DealOrder.status'=>DealOrder::STATUS_PENDING),'recursive'=>0));
		if(empty($dealOrder))
		{
			$this->errorMsg(__('Invalid URL!'));
			$this->redirect($this->referer());
			return;
		}
		$ipnData = null;
		$this->DealOrder->id = $id;
		if($this->DealOrder->setAsCompleted($id, $ipnData))
		{
			$this->successMsg(__('Order has been completed.'));
			$this->__mailOnOrderComplete($id);
		} else {
			$this->errorMsg(__('Order could not be completed.'));
		}
		$this->redirect($this->referer());
	}
	
	function admin_changeUsedStatus($id)
	{
		$dealOrder = $this->DealOrder->find('first',array('conditions'=>array('id'=>$id,'is_used'=>0),'recursive'=>-1));
		if(empty($dealOrder))
		{
			$this->errorMsg(__('Invalid URL!'));
			$this->redirect($this->referer());
			return;
		}
		if($this->DealOrder->markAllUsed($id))
		{
			$this->successMsg(__('Order has been marked as used.'));
		} else {
			$this->errorMsg(__('Order could not be marked as used.'));
		}
		$this->redirect($this->referer());
	}
	
	function __mailOnOrderComplete($dealOrderId)
	{
		$dealOrder = $this->DealOrder->findById($dealOrderId);
		if(empty($dealOrder))
		{
			return;
		}
		$dealCodes = Set::extract($dealOrder,"DealOrderCode.{n}.deal_code");
		$dealCodesHtml = implode(",  <br>", $dealCodes);
		$dealCodesText = implode(",  \n\r", $dealCodes);
		
		$this->Email->reset();
		$this->Email->to = $dealOrder['User']['email'];
		$this->Email->subject = cr('cmsConfig.Backend.siteName').__(" purchased deal's details");
		$this->Email->setFrom(cr('cmsConfig.Backend.websiteEmail'),cr('cmsConfig.Backend.siteName'));
		$this->Email->sendAs = 'both';
		$this->Email->template = 'deal_purchased';
		$this->set('dealTitle',$dealOrder['Deal']['title']);
		$this->set('dealUrl',cr('cmsConfig.Backend.siteUrl').$dealOrder['Deal']['viewUrl']);
		$this->set('myDealsUrl',cr('cmsConfig.Backend.siteUrl')."/deals/deal_orders/myDeals");
		$this->set('userName',$dealOrder['User']['username']);
		$this->set('dealAmount',$dealOrder['DealOrder']['amount']);
		$this->set('dealCodesHtml',$dealCodesHtml);
		$this->set('dealCodesText',$dealCodesText);
		$this->Email->send();
	}
	

	function myDeals()
	{
		$authedUserId = $this->Session->read("Auth.User.id");
		$conditions = array('DealOrder.user_id'=>$authedUserId, "DealOrder.status"=>DealOrder::STATUS_COMPLETE);
		
		if(!$this->DealOrder->Deal->isDealEnabled())
		{
			$this->errorMsg(__('Invalid URL', true));
			$this->redirect($this->referer());
			return;
		}
		if(!isset($this->paginate['conditions']))
		{
			$this->paginate['conditions'] = array();
		}
		
		$this->pageTitle = __("My purchased deals");
		if(!isset($this->paginate['conditions']))
		{
			$this->paginate['conditions'] = array();
		}
		$this->paginate['recursive'] = 1;
		$this->paginate['conditions'] = am($this->paginate['conditions'],$conditions);
		$this->paginate['order'] = array('DealOrder.created'=>"DESC");
		$deals = $this->paginate();
		$this->set('deals', $deals);
	}
	function prepareInvoice($orderId)
	{
		$order = $this->DealOrder->findById($orderId);
		$Paypal = new DealOrderPayment();
		if(empty($order))
		{
			$this->errorMsg(__("An error has occured while fetching data."));
			$this->redirect('/');
		} else if(cr("DealConfig.paypal_account") && $Paypal) {
			$ipnVars = $Paypal->getWebStandardPaymentInformation($order);
			$ipnVars['notify_url'] = Router::url(array("plugin"=>"deals","controller"=>"deal_orders","action"=>'paypalIpn',$orderId),true);
			$ipnVars['return'] = Router::url(array("plugin"=>"deals","controller"=>"deal_orders","action"=>'paypalReturn',$orderId),true);
			//$this->DealOrder->setAsProcessing($orderId);
			$this->set("ipnVars",$ipnVars);
			$this->set("paypalUrl",$Paypal->getPaypalUrl());
			$this->set("dealOrder",$order);
			//$this->log(array($order, $ipnVars),'ipn_call/deal_invoice_'.$orderId);
		} else {
			$this->errorMsg(__("An error has occured while initiating payment process."));
			$this->redirect('/');
		}
	}
	
	function paypalReturn($orderId)
	{
		$order = $this->DealOrder->findById($orderId);
		//$this->log($order ,'ipn_call/deal_return_'.$orderId);
		if(!empty($order))
		{
			if($order['DealOrder']['status'] == DealOrder::STATUS_COMPLETE)
			{
				$this->successMsg(__("Payment process has been completed successfully."));
			} else if($order['DealOrder']['status'] == DealOrder::STATUS_PENDING) {
				$this->errorMsg(__("Payment process could not be completed. Please try again."));
			} else {
				$this->errorMsg(__("Payment process failed. Please try again."));
			}
			$this->set('dealOrder', $order);
		} else {
			$this->errorMsg(__("Invalid URL."));
			$this->redirect('/');
		}
	}
	
	function paypalIpn($orderId)
	{
		$Paypal = new DealOrderPayment();
		$order = $this->DealOrder->findById($orderId);
		$this->log($_POST,"ipn_call/deal_order_".$orderId);
		//$this->log($order,'ipn_call/deal_order_'.$orderId);
		if(!empty($order) && $orderId)
		{
			if($Paypal->validateIpn($_POST)) 
			{
				//$this->log("passed first check: validateIpn",'ipn_call/deal_order_'.$orderId);
				if($Paypal->validateOrder($_POST,$order))
				{
					//$this->log("passed second check: validateOrder",'ipn_call/deal_order_'.$orderId);
					$this->DealOrder->setAsCompleted($orderId, $_POST);
					$this->__mailOnOrderComplete($orderId);
				} else {
					$this->DealOrder->setAsFailed($orderId, $_POST);
				}
			}
		}
		$this->_stop();
	}
	
	function dealCoupon($orderId, $dealOrderCode = null) 
	{
		$authedUserId = $this->Session->read("Auth.User.id");
		$dealOrder = $this->DealOrder->find("first",array("conditions"=>array("DealOrder.id"=>$orderId, "DealOrder.user_id"=>$authedUserId, "DealOrder.status"=>DealOrder::STATUS_COMPLETE)));
		if(!$orderId || empty($dealOrder))
		{
			$this->errorMsg(__("Invalid Deal"));
			$this->redirect("/");
		}
		
		$this->DealOrder->Deal->Listing->setEavStatus(true);
		$listing = $this->DealOrder->Deal->Listing->find("first",array("conditions"=>array("Listing.id"=>$dealOrder['Deal']['listing_id']),"recursive"=>0));
		$listingFieldProperties = $this->DealOrder->Deal->Listing->getAttributes($listing);
		
		$address = array();
		$fields = array('address1_field','address2_field','city_field','postal_code_field','state_field','country_field');
		foreach($fields as $field)
		{
			$listingFieldname = cr("MapConfig.".$field);
			if($listingFieldname && isset($listing['Listing'][$listingFieldname]))
			{
				$addressFieldValue = $listingFieldProperties->getShowValue($listingFieldname, $listing['Listing']);
				$address[$listingFieldname] = $addressFieldValue;
			}
		}
		
		$this->pageTitle = "";
		$this->layout = "plain";
		$this->set("dealOrder",$dealOrder);
		$this->set("listing",$listing);
		$this->set("listingAddress",$address);
		$this->set("dealOrderCode",$dealOrderCode);
		Configure::write("debug",0);
	}
	
}
?>